package com.yotoodesign.dianba.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MKMapViewListener;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.PoiOverlay;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.adapter.KtvAdapter;
import com.yotoodesign.dianba.adapter.TopAdapter;
import com.yotoodesign.dianba.app.GlobalApplication;
import com.yotoodesign.dianba.bean.Adv;
import com.yotoodesign.dianba.bean.BaseData;
import com.yotoodesign.dianba.bean.Ktv;
import com.yotoodesign.dianba.custom.xlistview.XListView;
import com.yotoodesign.dianba.custom.xlistview.XListView.IXListViewListener;
import com.yotoodesign.dianba.ui.CallbackListener;
import com.yotoodesign.dianba.ui.MainActivity;
import com.yotoodesign.dianba.util.Constant;
import com.yotoodesign.dianba.util.DataUtils;
import com.yotoodesign.dianba.util.GuidePageChangeListener;


public class KtvFragment extends BaseFragment implements IXListViewListener,CallbackListener{

	private ViewPager vpAdvs = null;
	private ImageView[] imgFocuses = null;
	private ImageView imageView = null;
	private AtomicInteger what = new AtomicInteger(0);
	
	private boolean isContinue = true;
	
	private Thread thread = null;
	
	private XListView ktvlist;
	private KtvAdapter ktvAdapter;
	private Handler mHandler;
	
	private KtvDetailFragment ktvDetailFragment;
	
	private MainActivity main;
	
	private BDLocation location ;
	private TextView tvLocation;
	private LinearLayout currentLocation;
	
	private MKSearch mMKSearch;
	
	private String curr;
	private ArrayList list;

	static MapView mMapView = null;
	MyLocationOverlay myLocationOverlay = null;
	LocationData locData = null;
	public MKMapViewListener mMapListener = null;
	/*
	 * 我的位置是否添加到地图中
	 */
	private boolean added = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		mHandler = new Handler();
		GlobalApplication app = (GlobalApplication)getActivity().getApplication();
		app.myListener.setKtvRef(this);
		
		main = GlobalApplication.getMainActivity();
		main.mLocClient.start();

		
		mMKSearch = GlobalApplication.getInstance().mMKSearch;
		app.searchListener.callback = this;
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ktv_fragment, container,false);
		TextView title = (TextView)view.findViewById(R.id.mainTitle);
		title.setText("周边KTV");
		
		ImageButton commonBack = (ImageButton)view.findViewById(R.id.commonBack);
		commonBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				GlobalApplication.getMainActivity().goHome();
			}
		});
		
		Button btnRefresh = (Button)view.findViewById(R.id.btnRefreshLoc);
		btnRefresh.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				refresh();
			}
		});
		
		currentLocation = (LinearLayout)view.findViewById(R.id.currentLocation);
		tvLocation = (TextView)view.findViewById(R.id.tvLocation);
		
		//地图信息
		mMapView = (MapView)view.findViewById(R.id.bmapView);
		mMapView.getController().setZoom(14);
        mMapView.getController().enableClick(true);
        mMapView.setBuiltInZoomControls(true);
        mMapListener = new MKMapViewListener() {
			@Override
			public void onMapMoveFinish() {
			}
			
			@Override
			public void onClickMapPoi(MapPoi mapPoiInfo) {
				// TODO Auto-generated method stub
				String title = "";
				if (mapPoiInfo != null){
					title = mapPoiInfo.strText;
					Toast.makeText(getActivity(),title,Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onGetCurrentMap(Bitmap b) {
			}

			@Override
			public void onMapAnimationFinish() {
			}
		};
		mMapView.regMapViewListener(GlobalApplication.getInstance().mBMapManager, mMapListener);
		
		return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		initViewPager();
	}
	
	/*
	 * 初始化Top10
	 */
	private void initViewPager() {
		vpAdvs = (ViewPager)getView().findViewById(R.id.vpAdvs);
		ViewGroup group = (ViewGroup)getView().findViewById(R.id.viewGroup);
		
		List<View> listAdvs = new ArrayList<View>();
		listAdvs.addAll(loadAdvs());
		
		imgFocuses = new ImageView[listAdvs.size()];
		for(int i = 0;i<listAdvs.size();i++){
			imageView = new ImageView(getActivity());
			imageView.setLayoutParams(new ViewGroup.LayoutParams(30,ViewGroup.LayoutParams.WRAP_CONTENT));
			imageView.setPadding(0,0,0,0);
			imgFocuses[i] = imageView;
			if(i == 0){
				imgFocuses[i].setBackgroundResource(R.drawable.banner_dian_focus);
			}else{
				imgFocuses[i].setBackgroundResource(R.drawable.banner_dian_blur);
			}
			group.addView(imgFocuses[i]);
		}
		
		vpAdvs.setAdapter(new TopAdapter(listAdvs));
		vpAdvs.setOnPageChangeListener(new GuidePageChangeListener(imgFocuses,what));
		vpAdvs.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					break;
				default:
					isContinue = true;
					break;
				}
				return false;
			}
		});
		
		/** 启动线程循环显示广告
		isContinue = true;
		
		thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					if( isContinue){
						viewHandler.sendEmptyMessage(what.get());
						whatHandler();
					}
				}
				
			}
		});
		
		thread.start();
		**/
	}

	@Override
	public void updateListView() {
		// TODO Auto-generated method stub
		
	}
	
	/*
	 * 加载广告列表
	 */
	private List<View> loadAdvs(){
		ArrayList<BaseData> advs = DataUtils.loadAdvs();
		
		List<View> views = new ArrayList<View>();
		for(int i = 0;i<advs.size();i++){
			View ktvAdv = LayoutInflater.from(getActivity()).inflate(R.layout.ktv_adv, null);
			
			ImageView adv = (ImageView)ktvAdv.findViewById(R.id.adv);
			adv.setBackgroundResource(R.drawable.ktv_adv);
			TextView tvTitle = (TextView)ktvAdv.findViewById(R.id.tvTitle);
			tvTitle.setText(((Adv)advs.get(i)).getName());
			views.add(ktvAdv);
		}
		return views;
	}
	
	/*
	 * 加载KTV列表
	 */
	private void loadKtvs(ArrayList<BaseData> ktvs){
		
		ktvlist = (XListView)getView().findViewById(R.id.ktvlist);
		ktvlist.setPullLoadEnable(false);
		ktvlist.setPullRefreshEnable(false);
		ktvlist.setXListViewListener(this);
		ktvlist.setOnItemClickListener(addItemClickListener());
		
		ktvAdapter = new KtvAdapter(getActivity());
		ktvAdapter.setKtvList(ktvs);
		ktvlist.setAdapter(ktvAdapter);
		
	}
	
	private void onLoaded() {
		ktvlist.stopRefresh();
		ktvlist.stopLoadMore();
		ktvlist.setRefreshTime("刚刚");
	}
	
	@Override
	public void onRefresh() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				onLoaded();
			}
		}, Constant.SECOND);
		
	}

	@Override
	public void onLoadMore() {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				loadMore();
				onLoaded();
			}
		}, Constant.SECOND);
		
	}
	
	//加载更多数据
	private void loadMore(){
		ArrayList<BaseData> list = ktvAdapter.getKtvList();
		int size = list.size();
		for(int i = size;i<size+10;i++){
			list.add(new Ktv("","量贩KTV"+(i+1),"合肥市包河区"+i+"号","",0,false));
		}
		ktvAdapter.setKtvList(list);
	}

	private AdapterView.OnItemClickListener addItemClickListener(){
		return new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//显示KTV详情
				Ktv ktv = (Ktv)ktvAdapter.getKtvList().get(position-1);
				showKtvDetail(Constant.TAG_KTV_DETAIL,ktv);
			}
		};
	}
	
	/*
	 * 显示KTV详情
	 */
	private void showKtvDetail(String tabId,Ktv ktv){
		if(ktv.isHasCaterDetails()){
			mMKSearch.poiDetailSearch(ktv.getId());
		}else{
			FragmentManager fm = getActivity().getSupportFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			//先hide主Fragment
			ft.hide(this);
			ktvDetailFragment = (KtvDetailFragment)fm.findFragmentByTag(tabId);
			if(ktvDetailFragment==null){
				try {
					ktvDetailFragment = new KtvDetailFragment();
					ktvDetailFragment.setData(ktv);
					ft.add(R.id.realtabcontent,ktvDetailFragment, tabId);
					//添加到后退堆栈里
					ft.addToBackStack(tabId);
				} catch (Exception e) {
					Log.i(Constant.DIANBA,"add to back stack error");
				}						
			}else{
				ft.attach(ktvDetailFragment);						
			}
			
			ft.commit();
			
			MainActivity mainActivity = (MainActivity)this.getActivity();
			mainActivity.setCurrentFragment(ktvDetailFragment);
		}
	}
	
	public BDLocation getLocation() {
		return location;
	}

	public void setLocation(BDLocation location) {
		this.location = location;
	}
	
	/*
	 * 更新位置信息，并搜索周边KTV
	 */
	public void updateLocation(BDLocation location){
		this.location = location;
		
		main.mLocClient.stop();
		//当前位置点
		GlobalApplication.getInstance().currentPoint = new GeoPoint((int) (location.getLatitude() * 1E6),
						(int) (location.getLongitude() * 1E6));
				
		tvLocation.setText(location.getAddrStr());
		this.curr = location.getAddrStr();
		//周边KTV搜索
		mMKSearch.poiSearchNearBy("KTV",GlobalApplication.getInstance().currentPoint, 5000);
	}

	@Override
	public void execute(ArrayList result) {
		ArrayList<BaseData> list = new ArrayList<BaseData>();
		
		
		GeoPoint curr = GlobalApplication.getInstance().currentPoint;
		for(int i = 0;i<result.size();i++){
			MKPoiInfo info = (MKPoiInfo)result.get(i);
			Double distance = DistanceUtil.getDistance(curr, info.pt);
			Ktv ktv = new Ktv(info.uid,info.name,info.address,info.phoneNum,distance,info.hasCaterDetails);
			list.add(ktv);
		}
		
		//先排序
		Collections.sort(list, new SortByDistance());
				
		loadKtvs(list);
		this.list = list;
		
		// 将poi结果显示到地图上
		PoiOverlay poiOverlay = new PoiOverlay(getActivity(), mMapView);
		poiOverlay.setData(result);
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(poiOverlay);
		
        //我的位置
        myLocationOverlay = new MyLocationOverlay(mMapView);
        locData = new LocationData();
        locData.latitude = location.getLatitude();
        locData.longitude = location.getLongitude();
        locData.accuracy = location.getRadius();
        locData.direction = location.getDerect();
        
	    myLocationOverlay.setData(locData);
	    mMapView.getOverlays().add(myLocationOverlay);
		
		myLocationOverlay.enableCompass();
		mMapView.refresh();
		
		// 当ePoiType为2（公交线路）或4（地铁线路）时， poi坐标为空
		for(int i = 0;i<result.size();i++){
			MKPoiInfo info = (MKPoiInfo)result.get(i);
			if (info.pt != null) {
				mMapView.getController().animateTo(info.pt);
				break;
			}
		}
	}
	
	
	
	class SortByDistance implements Comparator<BaseData> {
		@Override
		public int compare(BaseData arg0, BaseData arg1) {
			Ktv a = (Ktv)arg0;
			Ktv b = (Ktv)arg1;
			if (a.getDistance() > b.getDistance())
				return 1;
			else
				return -1;
		}
		
	}
	
	private void refresh(){
		tvLocation.setText(getString(R.string.locating));
		main.mLocClient.start();
	}

	@Override
	public void onPause() {
		mMapView.onPause();
		super.onPause();
	}   

	@Override
	public void onResume() {
		mMapView.onResume();
		
		if(this.curr!=null){
			tvLocation.setText(this.curr);
			loadKtvs(list);
		}else{
			tvLocation.setText(getString(R.string.locating));
		}
		
		super.onResume();
	}
	
	    
    @Override
	public void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    }
    
	@Override
	public void onDestroyView() {
		if (main.mLocClient != null)
            main.mLocClient.stop();
        mMapView.destroy();
		super.onDestroyView();
	}
}
